package com.clearliang.alarmnotice.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clearliang.alarmnotice.bean.AlarmBean;
import com.clearliang.alarmnotice.receiver.AlarmReceiver;

import java.util.Calendar;
import java.util.List;

import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM;
import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM_DETAILS;

/**
 * Created by ClearLiang on 2019/2/28
 * <p>
 * Function :每日零点进行判断今天是否有任务
 */
public class CheckAlarmService extends Service {

    private boolean isCanStart = false;     //是否可以开启任务时钟

    //创建服务时调用
    @Override
    public void onCreate() {
        super.onCreate();
        //LogUtils.e("onCreate");
        String alarmDetails = SPUtils.getInstance(SP_ALARM).getString(SP_ALARM_DETAILS, "");
        if (!TextUtils.isEmpty(alarmDetails)) {
            //任务列表
            List<AlarmBean> alarmBeanList = JSON.parseArray(alarmDetails, AlarmBean.class);
            for (int i = 0; i < alarmBeanList.size(); i++) {
                if (alarmBeanList.get(i).isIsOpen()) {
                    isCanStart = true;
                    break;
                }
            }
        }
    }

    //服务执行的操作
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //LogUtils.e("onStartCommand", JSON.toJSONString(alarmBeanList));
        if (isCanStart) {
            refreshAlarm();
            LogUtils.e("任务开启");
        }else {
            LogUtils.e("尚未检测到任务开启");
            ToastUtils.showShort("尚未检测到任务开启");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //销毁服务时调用
    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelAlarm();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private PendingIntent pi;
    private AlarmManager am;

    private void refreshAlarm() {
        pi = PendingIntent.getBroadcast(this, 0, getMsgIntent(), 0);
        am = (AlarmManager) getSystemService(ALARM_SERVICE);

        if (Build.VERSION.SDK_INT < 19) {
            am.set(AlarmManager.RTC_WAKEUP, getTimeDiff(), pi);
        } else {
            am.setExact(AlarmManager.RTC_WAKEUP, getTimeDiff(), pi);
        }
        /*new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshAlarm();
            }
        }, AlarmManager.INTERVAL_DAY);*/
    }

    public long getTimeDiff() {
        //这里设置的是当天的15：55分，注意精确到秒，时间可以自由设置
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 1);
        ca.set(Calendar.SECOND, 0);
        return ca.getTimeInMillis();
    }

    private Intent getMsgIntent() {
        //AlarmReceiver 为广播在下面代码中
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.setAction(AlarmReceiver.BC_ACTION);
        intent.putExtra("msg", "闹钟开启");
        return intent;
    }

    //取消定时任务的执行
    private void cancelAlarm() {
        if (am != null) {
            am.cancel(pi);
            Intent intent = new Intent(this, AlarmReceiver.class);
            intent.setAction(AlarmReceiver.BC_ACTION_CLONE);
            intent.putExtra("msg", "关闭闹钟");
        }
    }

}
